package com.huayue.point.filter;

import com.alibaba.fastjson.JSONObject;
import com.huayue.point.bean.ResultBean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
@WebFilter(urlPatterns = "/*", filterName = "authFilter")
public class AuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        HttpSession session = httpServletRequest.getSession();
        if (session != null && session.getAttribute("user") != null) {
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        } else {
            String requestURI = httpServletRequest.getRequestURI();
            if (requestURI.startsWith("/user/login")) {
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
            ResultBean resultBean = new ResultBean();
            resultBean.setMessage("Please login.");
            resultBean.setStatus(0);
            servletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            servletResponse.getOutputStream().write(JSONObject.toJSONString(resultBean).getBytes("UTF-8"));
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void destroy() {

    }
}